package hibernate2;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

public class PlayerDao {

	private Session session;

	public PlayerDao(Session session) {
		super();
		this.session = session;
	}

	public List<Player> list() {
		Query<Player> query = session.createQuery("from Player", Player.class);

		return query.getResultList();
	}

	public List<Player> listByName(String name) {
		Query<Player> query = session.createQuery("from Player where username like:name", Player.class);
		query.setParameter("name", "%" + name + "%");

		return query.getResultList();
	}

	public List<Player> listName(String name) {
		Query<Player> query = session.createQuery("from Player where username=name", Player.class);
		return query.getResultList();
	}

	public Player getPlayerById(int id) {
		return session.get(Player.class, id);
	}

	public void insert(Player player){
		Transaction ts = session.beginTransaction();
		try{
			session.save(player);
			ts.commit();
		}catch(Exception e){
			ts.rollback();
		}
	}
	
	public void delete(Player player){
		Transaction ts = session.beginTransaction();
		try{
			session.delete(player);
			ts.commit();
		}catch(Exception e){
			ts.rollback();
		}
	}
	
	public void update(Player player){
		Transaction ts = session.beginTransaction();
		try{
			session.update(player);
			ts.commit();
		}catch(Exception e){
			ts.rollback();
		}
	}
}
